package com.hctforgreen.greenservice;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;

import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.LoadingInfoEntity;
import com.hctforgreen.greenservice.ui.widget.MyCustomDialog;
import com.hctforgreen.greenservice.utils.AsyncImageLoader;
import com.hctforgreen.greenservice.utils.AsyncImageLoader.ImageCallback;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.LanguageSettingUtil;
import com.hctforgreen.greenservice.utils.LoginInStoreUtil;
import com.hctforgreen.greenservice.utils.Md5Util;
import com.hctforgreen.greenservice.utils.ScreenUtil;
import com.hctforgreen.greenservice.utils.SelectStoreUtil;
import com.hctforgreen.greenservice.utils.ThemeStoreUtil;
import com.hctforgreen.greenservice.utils.WelcomePicUtil;
import com.mato.sdk.proxy.Proxy;
import com.umeng.analytics.MobclickAgent;

import java.util.Locale;

import cn.jpush.android.api.JPushInterface;

/**
 * 欢迎闪屏页面
 *
 * @author Tallen Zhai
 *         <p/>
 *         增加6.0权限申请 20161202
 * @author 390697
 */
public class WelcomeActivity extends ParentActivity {
    final String TAG = "WelcomeActivity";
    private static final long LOADING_TIME = 100;
    private static final long SWITCH_TIME = 10000;
    private boolean bFirstSwitchActivity = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.rightScroll = false;
        if (initLanguage()) {
            return;
        }

        Proxy.start(this);
        setContentView(R.layout.activity_welcome);
        initSwitchOnClick();
        initWebView();
        loadWelcomePic(WelcomePicUtil.get(WelcomeActivity.this));
        getLoadingInfo();
        checkPermisssion();
    }

    // 语言设置
    private boolean initLanguage() {
        String secondTime = getIntent().getStringExtra("second_time");
        if (secondTime == null || secondTime.trim().length() == 0) {
            int setting = LanguageSettingUtil.get(this);
            switch (setting) {
                case 0:// 中文版
                    switchLanguage(Locale.CHINESE);
                    return true;
                case 1:// 英文版
                    switchLanguage(Locale.ENGLISH);
                    return true;
            }
            return false;
        }
        return false;
    }

    private void switchLanguage(Locale locale) {
        Resources resources = getResources();// 获得res资源对象
        Configuration config = resources.getConfiguration();// 获得设置对象
        DisplayMetrics dm = resources.getDisplayMetrics();// 获得屏幕参数：主要是分辨率，像素等。
        config.locale = locale; // 简体中文
        resources.updateConfiguration(config, dm);

        Intent intent = new Intent(new Intent(this, WelcomeActivity.class));
        intent.putExtra("second_time", "true");
        startActivity(intent);
        finish();

    }

    private void initSwitchOnClick() {
        final View touchV = findViewById(R.id.tv_touch);
        touchV.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    //自此处需要判断一下权限是否都获得了
                    hasPhonePermission = ActivityCompat.checkSelfPermission(WelcomeActivity.this, Manifest.permission.READ_PHONE_STATE);
                    hasExternalPermission = ActivityCompat.checkSelfPermission(WelcomeActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    //只有在三个权限都获取的情况下才能自动登录
                    if ((hasPhonePermission + hasExternalPermission)!=0) {
                        return;
                    }
                }
                welcome(LOADING_TIME);

            }
        });
    }

    private void initWebView() {
        final WebView webView = (WebView) findViewById(R.id.wv_top);
        webView.setBackgroundColor(0); // 设置背景色
        // 取消滚动条

        dealWebViewParams(webView);
    }

    private void dealWebViewParams(final WebView webView) {

        ImageView topIv = (ImageView) findViewById(R.id.iv_top);
        ScreenUtil screenUtil = new ScreenUtil();
        int screenWidth = screenUtil.getScreenWidth(this);

        if (!screenUtil.bLongScreen(WelcomeActivity.this)) {
            int webViewHeight = (screenWidth * 996 / 800);
            LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
                    webViewHeight);
            webView.setLayoutParams(params);
            topIv.setLayoutParams(params);
        } else if (screenUtil.bLongScreen(WelcomeActivity.this)) {
            int webViewHeight = (screenWidth * 1537 / 1082);
            LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
                    webViewHeight);
            webView.setLayoutParams(params);
            topIv.setLayoutParams(params);
        }

    }

    @Override
    protected void onResume() {
        JPushInterface.onResume(this);
        MobclickAgent.onResume(this);
        super.onResume();
    }

    /**
     * 危险权限有：
     * android.permission.READ_CONTACTS 读取联系人
     * android.permission.READ_PHONE_STATE 读取电话状态
     * android.permission.CALL_PHONE 拨打电话 （暂不申请）
     * android.permission.READ_CALL_LOG 读取通话记录（暂不申请）
     * android.permission.WRITE_CALL_LOG 修改通话记录（暂不申请）
     * android.permission.CAMERA 获取拍照权限
     * android.permission.ACCESS_FINE_LOCATION 通过gps获取定位权限
     * android.permission.ACCESS_COARSE_LOCATION 通过WiFi和移动基站获取定位权限
     * android.permission.READ_EXTERNAL_STORAGE 读取内存卡 下载资料，设置，
     * android.permission.WRITE_EXTERNAL_STORAGE 写内存卡
     * android.permission.RECORD_AUDIO 录音权限（暂不申请）
     */
    private final int REQUEST_PHONE_PERMISSION_CODE = 1;
    private final int REQUEST_EXTERNAL_PERMISSION_CODE = 2;

    private int hasPhonePermission;
    private int hasExternalPermission;

    private void checkPermisssion() {
        try {
            //要判断手机的版本是不是6.0以上的
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                //按照原有的方式在manifest.xml中声明
                welcome(SWITCH_TIME);
                return;
            }
            hasPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
            hasExternalPermission = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (hasPhonePermission != PackageManager.PERMISSION_GRANTED) {
                //没有相应的权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE,Manifest.permission.CALL_PHONE,Manifest.permission.READ_CALL_LOG,
                        Manifest.permission.WRITE_CALL_LOG}, REQUEST_PHONE_PERMISSION_CODE);
            }else if (hasExternalPermission != PackageManager.PERMISSION_GRANTED){
              //当电话权限已经授权同意，则需检查读写文件的权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_EXTERNAL_PERMISSION_CODE);
            }

            if (hasExternalPermission == PackageManager.PERMISSION_GRANTED && (hasPhonePermission == PackageManager.PERMISSION_GRANTED)){
                //当两项权限都有时，直接跳转页面
                welcome(SWITCH_TIME);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过调用6.0系统权限申请结果的回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PHONE_PERMISSION_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_DENIED){
                    //该权限被拒绝了
                showDialog(permissions[0]);
            }else if (ActivityCompat.checkSelfPermission(WelcomeActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
                //当同意了电话权限后，需要检查读写文件的权限是否已经授权同意了，如果同意，跳转页面
                welcome(LOADING_TIME);
            }else if(ActivityCompat.checkSelfPermission(WelcomeActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED){
                ActivityCompat.requestPermissions(WelcomeActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},REQUEST_EXTERNAL_PERMISSION_CODE);
            }
        }else if (requestCode == REQUEST_EXTERNAL_PERMISSION_CODE){
            if (grantResults[0] == PackageManager.PERMISSION_DENIED){
                //该权限被拒绝了
                showDialog(permissions[0]);
            }else if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
                welcome(LOADING_TIME);
            }
        }
    }

    //当用户拒绝了某项权限 或者权限未申请，但是系统不弹框的情况下，需要自己弹框提示用户去设置
    private void showDialog(String permission){
        String content="";
        if (permission.equals(Manifest.permission.READ_PHONE_STATE)){
            content=getString(R.string.telephone);
        }else if (permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
            content=getString(R.string.read_write_external_file);
        }
            new MyCustomDialog().showAlert(this, getString(R.string.apply_for_permission), getString(R.string.permission_tip) + content + getString(R.string.permission), getString(R.string.set_permission_now), getString(R.string.dont_set), new MyCustomDialog.OnAlertSelected() {
                @Override
                public void onClick(int whichButton) {
                    if (whichButton == MyCustomDialog.NO) {
                        //直接退出应用
                        System.exit(0);
                    } else {
                        //直接跳转至手机设置的应用管理器中
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.MAIN");
                        intent.setClassName("com.android.settings", "com.android.settings.ManageApplications");
                        startActivity(intent);
                        System.exit(0);
                    }
                }
            });

    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
        MobclickAgent.onPause(this);
        new MyCustomDialog().destroyDialog();
    }

    private void welcome(final long longTime) {
        final Handler activitySwitcher = new Handler() {
            public void handleMessage(Message msg) {
                if (bFirstSwitchActivity) {
                    return;
                }
                /**
                 * 判断是否为首次安装
                 */
                if (LoginInStoreUtil.isFirstInstall(WelcomeActivity.this)) {
                    ThemeStoreUtil.saveSkinId(WelcomeActivity.this,
                            "R.drawable.ic_default_activity_bg");
                    SelectStoreUtil.save(WelcomeActivity.this, 0);//
                    Intent i = new Intent();
                    i.setClass(WelcomeActivity.this, TipsActivity.class);
                    startActivity(i);

                    finish();
                } else {
                    Intent i = new Intent();
                    if (getIntent().getExtras() != null
                            && getIntent().getStringExtra("second_time") == null) {
                        i.putExtras(getIntent().getExtras());
                    }
                    i.setClass(WelcomeActivity.this, LoginActivity.class);
                    startActivity(i);
                    finish();
                }
                bFirstSwitchActivity = true;
            }
        };
        new Thread() {
            public void run() {
				try {
					Thread.sleep(longTime);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

                activitySwitcher.sendEmptyMessage(0);

            }
        }.start();

    }

    //获取图片的路径
    private String buildGifUrl(String id) {
        ScreenUtil screenUtil = new ScreenUtil();
        String sIndex = screenUtil.bLongScreen(WelcomeActivity.this) ? HctConstants.NET_GIF_INDEX_LONG
                : HctConstants.NET_GIF_INDEX_SHORT;
        return HctConstants.NET_URL + HctConstants.NET_LOADING_MOBILE_PATH
                + HctConstants.OUT_PIC_STREAM_ACTION
                + HctConstants.NET_GIF_ID_HEADER + id + sIndex;
    }

    private void loadWelcomePic(final LoadingInfoEntity entity) {
        String gifUrl = buildGifUrl(entity.id);
        AsyncImageLoader imageLoader = new AsyncImageLoader();
        //通过路径去加载图片，异步任务
        Drawable cacheDrawable = imageLoader.loadDrawable(gifUrl, this, true,
                new ImageCallback() {

                    @Override
                    public void imageLoaded(Drawable imageDrawable,
                                            String imageUrl) {
                        if (imageDrawable != null) {
                            renderWeclomePic("file://"
                                    + HctConstants.DEFAULT_ROOT_PATH
                                    + HctConstants.DEFAULT_CACHE_STORE_PATH
                                    + imageUrl, entity.message);
                        } else {
                        }
                    }
                });
        if (cacheDrawable != null) {
            final String md5Url = Md5Util.md5(gifUrl);
            renderWeclomePic("file://" + HctConstants.DEFAULT_ROOT_PATH
                            + HctConstants.DEFAULT_CACHE_STORE_PATH + md5Url,
                    entity.message);
        } else {

        }
    }

    //渲染启动页面的图片以及提示文字
    private void renderWeclomePic(String filePath, String sMessage) {
        final WebView webView = (WebView) findViewById(R.id.wv_top);

        String html = "<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes\" /></head><body style=\"padding:0;margin:0;width:100%;height:100%;\"><img style=\"width:100%;height:100%;border:0;margin:0;padding:0;\" src=\""
                + filePath + "\"></body>";
        webView.loadDataWithBaseURL(null, html, "text/html", "uft-8", null);

        /**
         * 图片上的文字
         */
        final TextView messageTv = (TextView) findViewById(R.id.tv_message);

        if (sMessage.trim().equals("")) {
            messageTv.setVisibility(View.GONE);
        } else {
            messageTv.setText(sMessage);
            messageTv.setVisibility(View.VISIBLE);
        }

    }

    //获取启动页面的图片以及文字信息
    private void getLoadingInfo() {

        final Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                HctResult dnsResult = new HctResult();
                switch (msg.what) {
                    case HctConstants.STATUS_SUCCESS:
                        dnsResult = (HctResult) msg.obj;
                        LoadingInfoEntity entity = (LoadingInfoEntity) dnsResult.data;
                        WelcomePicUtil.save(WelcomeActivity.this, entity);
                        break;

                    case HctConstants.STATUS_FAILD:

                        break;
                }
            }
        };

        new Thread() {
            public void run() {
                Message message = new Message();
                try {
                    HctController controller = new HctController(
                            WelcomeActivity.this);
                    HctResult result = controller.getLoadingInfo();
                    if (result.status == HctConstants.STATUS_SUCCESS) {
                        message.what = result.status;
                        message.obj = result;
                    } else {
                        message.what = HctConstants.STATUS_FAILD;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                handler.sendMessage(message);
            }
        }.start();
    }
}
